<template>
  <div class="screen-adapter" :style="style">
    <slot />
  </div>
</template>

<script>
export default {
  props: {
    width: {
      type: String,
      default: '1920'
    },
    height: {
      type: String,
      default: '1080'
    }
  },
  data() {
    return {
      style: {
        width: this.width + 'px',
        height: this.height + 'px',
        transform: 'scale(1) translate(-50%, -50%)'
      }
    }
  },
  mounted() {
    this.setScale()
    window.addEventListener('resize', this.debounce(this.setScale, 100))
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.debounce(this.setScale, 100))
  },
  methods: {
    // 防抖函数
    debounce(fn, delay) {
      let timer = null
      return function() {
        if (timer) clearTimeout(timer)
        timer = setTimeout(() => fn.apply(this), delay)
      }
    },
    // 获取缩放比例
    getScale() {
      const w = window.innerWidth / parseFloat(this.width)
      const h = window.innerHeight / parseFloat(this.height)
      return w < h ? w : h
    },
    // 设置缩放
    setScale() {
      this.style.transform = `scale(${this.getScale()}) translate(-50%, -50%)`
    }
  }
}
</script>

<style scoped>
.screen-adapter {
  transform-origin: 0 0;
  position: absolute;
  left: 50%;
  top: 50%;
  transition: 0.3s;
  background-color: #0f1624;
  overflow: hidden;
}
</style> 